import React, { useEffect, useRef, useState } from "react";
import { fabric } from "fabric-with-erasing";
import _EE_ from "../EventEmitter";
import { directiveEnum } from "../index";
import getBrush from "../getBrush";
import animationBtns from "./animationList";
import "./index.less";
import { Button } from "antd";
type propsTypes = {
  directive: directiveEnum;
};
let currentImage: any = null;
let cropRect: any = null;
function Draw({ directive }: propsTypes) {
  const [cursorClaName, setCursoClasName] = useState("cursor-select");
  const [btnLoading, setBtnLoading] = useState<boolean>(true);
  const canvasEl = useRef<HTMLCanvasElement>(null);
  const fabricRef = useRef<any>(null); //当前画板实例
  const currentLine = useRef<any>(null);
  const isDrawing = useRef<boolean>(false); // 是否第一条线
  const lastPoint = useRef<any>(null); // 上一个点
  const rectAnimation = useRef<any>(true);
  useEffect(() => {
    const options = {
      isDrawingMode: true,
      width: window.innerWidth,
      height: window.innerHeight,
    };
    // 保存画布实例以便后续操作
    fabricRef.current = new fabric.Canvas(canvasEl.current as HTMLCanvasElement, options);
    //监听复制粘贴 删除 事件
    window.addEventListener("keydown", handleKeydown);

    _EE_.on("_fabric_add_image_", addImage);
    // _EE_.on("_fabric_execution_instruction_", excuteDirective);

    return () => {
      fabricRef.current.dispose();
      window.removeEventListener("keydown", handleKeydown);
      // _EE_.removeListener("_fabric_add_image_");
      // _EE_.removeListener("_fabric_execution_instruction_");
    };
  }, []);
  //监听当前是那个操作
  useEffect(() => {
    //笔刷操作
    if ([directiveEnum.PENCIL, directiveEnum.MARKPEN, directiveEnum.ERASER].includes(directive)) {
      fabricRef.current.isDrawingMode = true;
      fabricRef.current.freeDrawingBrush = getBrush(directive, fabricRef.current, {});
    } else if (directive === directiveEnum.POLYLINE) {
      //连续画线 钢笔
      fabricRef.current.isDrawingMode = false;
      fabricRef.current.on("mouse:down", handlPolylineDown);
      fabricRef.current.on("mouse:move", handlPolylineMove);
    } else if (directive === directiveEnum.HAND) {
      //选择
      fabricRef.current.isDrawingMode = false;
    } else if (directive === directiveEnum.IMAGE) {
      //图片
      fabricRef.current.isDrawingMode = false;
    } else if (directive === directiveEnum.ANIMATION) {
      //动画
      setBtnLoading(false);
      fabricRef.current.isDrawingMode = false;
      const rect = getBrush(directive, fabricRef.current, {});
      fabricRef.current.add(rect);
      rect.animate("opacity", 1, {
        duration: 800, // 动画持续时间为 1 秒
        onChange: fabricRef.current.renderAll.bind(fabricRef.current), // 动画过程中重新渲染画布
        onComplete: () => {
          console.log("动画完成！");
        },
        easing: fabric.util.ease.easeOutBounce, // 使用缓动函数
      });
      rectAnimation.current = rect;
    }
    setCursoClasName(getCursorClass(directive));
    return () => {
      fabricRef.current.remove(rectAnimation.current);
      setBtnLoading(true);
      fabricRef.current.off("mouse:down", handlPolylineDown);
      fabricRef.current.off("mouse:move", handlPolylineMove);
    };
  }, [directive]);
  //操作图片
  const addImage = (imageUrl: string) => {
    fabric.Image.fromURL(imageUrl, (img: any) => {
      const canvas = fabricRef.current;
      // 等比缩放60%
      const scale = 0.6;
      img.scale(scale);

      // 计算居中位置
      const centerX = canvas.width / 2;
      const centerY = canvas.height / 2;

      img.set({
        left: centerX - (img.width * scale) / 2,
        top: centerY - (img.height * scale) / 2,
        originX: "left",
        originY: "top",
      });

      canvas.add(img);
      canvas.renderAll();
      currentImage = img;
    });
  };

  //鼠标按下画线
  const handlPolylineDown = (event: any) => {
    let currentCircle = null; // 当前绘制的空心圆
    const pointer = fabricRef.current.getPointer(event.e);
    const x = pointer.x;
    const y = pointer.y;

    if (!isDrawing.current) {
      // 第一次点击，记录起点
      lastPoint.current = { x, y };
      isDrawing.current = true;
    } else {
      // 每次点击绘制一条线
      // 画线
      currentLine.current = new fabric.Line([lastPoint.current.x, lastPoint.current.y, x, y], {
        stroke: "black",
        strokeWidth: 2,
      });

      // 画空心圆
      currentCircle = new fabric.Circle({
        left: x - 5,
        top: y - 5,
        radius: 5,
        fill: "transparent",
        stroke: "black",
        strokeWidth: 2,
      });
      // 添加到画布
      fabricRef.current.add(currentLine.current);
      fabricRef.current.add(currentCircle);

      // 更新上一个点为当前点击点
      lastPoint.current = { x, y };
    }
  };
  //鼠标移动画线
  const handlPolylineMove = (event: any) => {
    if (!isDrawing.current || !lastPoint.current) return;

    const pointer = fabricRef.current.getPointer(event.e);

    const x = pointer.x;
    const y = pointer.y;

    // 如果已有临时线条，移除
    if (currentLine.current) {
      fabricRef.current.remove(currentLine.current);
    }

    // 绘制临时线条
    currentLine.current = new fabric.Line([lastPoint.current.x, lastPoint.current.y, x, y], {
      stroke: "black",
      strokeWidth: 2,
    });

    // 添加临时线条到画布
    fabricRef.current.add(currentLine.current);
  };
  //键盘事件
  const handleKeydown = (e: KeyboardEvent) => {
    if (e.key === "Delete" || e.key === "Backspace") {
      Delete();
    } else if ((e.ctrlKey || e.metaKey) && e.key === "c") {
      copy();
    } else if ((e.ctrlKey || e.metaKey) && e.key === "v") {
      paste();
    } else if (e.key === "Escape") {
      _EE_.emit("_set_directive", "hand");
      fabricRef.current.off("mouse:down", handlPolylineDown);
      fabricRef.current.off("mouse:move", handlPolylineMove);

      if (currentLine.current) {
        fabricRef.current.remove(currentLine.current);
        currentLine.current = null;
        isDrawing.current = false;
        lastPoint.current = null;
      }
    }
  };
  // 复制
  const copy = () => {};
  //粘贴
  const paste = () => {};
  //删除
  const Delete = () => {
    const activeObjects = fabricRef.current.getActiveObjects(); // 获取选中的对象
    console.log(activeObjects, "-----");

    if (activeObjects.length > 0) {
      activeObjects.forEach((obj: any) => {
        fabricRef.current.remove(obj); // 删除对象
      });
      fabricRef.current.discardActiveObject(); // 清除选中状态
      fabricRef.current.requestRenderAll(); // 重新渲染画布
    }
  };
  //获取类名 切换鼠标样式
  const getCursorClass = (directive: directiveEnum) => {
    // console.log(directive, "-----dir");
    switch (directive) {
      case "hand":
        return "reset-cursor hand";

      case "pencil":
        return "reset-cursor pencil";
      case "markPen":
        return "reset-cursor markPen";

      case "eraser":
        return "reset-cursor eraser";

      case "polyline":
        return "reset-cursor polyline";
      default:
        return "reset-cursor";
    }
  };
  //动画处理
  const handleAnimation = (ani: string) => {
    setBtnLoading(true);
    let rect = rectAnimation.current;
    let canvas = rect.animate(
      { left: rect.left === 70 ? 500 : 70 },
      {
        duration: 1000,
        onChange: () => fabricRef.current.requestRenderAll(),
        onComplete: function () {
          setBtnLoading(false);
        },
        easing: fabric.util.ease[ani],
      },
    );
  };
  return (
    <div className={cursorClaName}>
      <div
        className={`absolute left-16 z-50 ${directive === directiveEnum.ANIMATION ? "top-10" : "-top-10"} transition-all duration-800 `}
      >
        {animationBtns.map((btnText, idx) => (
          <Button
            disabled={btnLoading}
            key={idx}
            style={{ marginRight: "10px" }}
            onClick={() => handleAnimation(btnText)}
          >
            {btnText}
          </Button>
        ))}
      </div>
      <canvas width="100vw" height="100vh" ref={canvasEl} style={{ cursor: "unset" }} />
    </div>
  );
}

export default Draw;
